﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MarkControle.Models;
using MarkControle.ActionFilters;

namespace MarkControle.Controllers
{   

    
    
    
    [Authorize]
    [HandleError]
    [LoginFilter]
   public class HomeController : Controller 
    {

       
        
        public ActionResult ViewCadtarif()
        {
            ViewData["errdat"] = (string)Session["errdat"];
            Session["errdat"] = null;

            return View("CadastroTarefa");
        }
        
        [HttpPost]
        public ActionResult Cadastratarif(tarefa pac)
        {
            if (!ModelState.IsValid)
            {
                return View("CadastroTarefa");
            }
            if (DateTime.DaysInMonth(pac.C, pac.B) >= pac.A)
            {
                DateTime data = new DateTime(pac.C, pac.B, pac.A);
                if (DateTime.Compare(data, DateTime.Today) < 0)
                {
                    ViewData["errdat"] = "Data invalida";
                    return View("CadastroTarefa");
                }
                string[] encar = new string[3];
                encar[0] = pac.Enca1;encar[1] = pac.Enca2; encar[2] = pac.Enca3;
                Login test=new Login();
                if (!test.Responsavel(encar[0]))
                {
                    ModelState.AddModelError("encar1", "1º Responsavel não encontrado!");
                    return View("CadastroTarefa");
                }
                if (encar[1] != null && !test.Responsavel(encar[1]))
                {
                    ModelState.AddModelError("encar2", "2º Responsavel não encontrado!");
                    return View("CadastroTarefa");
                }
                else if(encar[1] == null)
                    encar[1]="";
                if (encar[2] != null && !test.Responsavel(encar[2]))
                {
                     ModelState.AddModelError("encar3","3º Responsavel não encontrado!");
                    return View("CadastroTarefa");
                }
                else if(encar[2] == null)
                    encar[2]="";
                
                tarefa nova = new tarefa(data, pac.Comentarios, pac.Informacoes, encar, 0,DateTime.Now,0,pac.Priori);
                
                string tar = "tarifmes" + nova.Prazo.Month.ToString() + "a" + nova.Prazo.Year.ToString();
                Session[tar]=null;
                nova.Adicionabanco();
                Session["errdat"] = "Cadastro realizado com sucesso!";

                return RedirectToAction("ViewCadtarif");
            }
            else
            {
                ViewData["errdat"] = "Data invalida";
                return View("CadastroTarefa");
            }
        }


        public ActionResult Next()
        {
            
            int m = (int)Session["tempmes"] + 1;
            int a = (int)Session["tempano"];
            if (m == 13)
            {   m = 1; a++;   }

            string tabindex = "tabela" + a.ToString();
            string tarifmesindex = "tarifmes" + m.ToString() +"a"+ a.ToString();
            ViewData["ano"] = a;
            ViewData["mes"] = m;
            if (Session[tarifmesindex] != null)
            {  ViewData["tabelames"] = Session[tabindex];
               return View("Index");
            }
            TabelaMes notab;

            if (Session[tabindex] == null)
                notab = new TabelaMes(a);
            else
                notab = (TabelaMes)Session[tabindex];
            
            
            notab.Atualiza(m, a);
            Session[tarifmesindex] = notab.Tarifs;
            Session[tabindex] = notab;
            ViewData["tabelames"] = notab;

           
            return View("Index");
        }



        public ActionResult Diaria(FormCollection form) {


            try { Session["tempdia"] = Int32.Parse(form["dia"]); }
            catch { }

            int m = (int)Session["tempmes"];
            int d = (int)Session["tempdia"];
            int a = (int)Session["tempano"];
            List<tarefa> tarifdia= new List<tarefa>();
            List<tarefa> tottarifas= (List<tarefa>)Session["tarifmes"+m.ToString()+"a"+a.ToString()];
            DateTime dia= new DateTime(a,m,d);
            foreach (tarefa taref in tottarifas)
            {
                if(DateTime.Compare(taref.Prazo,dia)==0)
                {
                    tarifdia.Add(taref);
                }
            }
            ViewData["listtarefas"] = tarifdia;
            
            return View();
        }



        public ActionResult Back()
        {
            int a = (int)Session["tempano"];
            int m = (int)Session["tempmes"]-1;
            if (m == 0)
            { m = 12; a--; }
            string tabindex = "tabela" + a.ToString();
            string tarifmesindex = "tarifmes" + m.ToString() +"a"+ a.ToString();

            ViewData["mes"] = m;
            ViewData["ano"] = a;
            if (Session[tarifmesindex] != null)
            {
                ViewData["tabelames"] = Session[tabindex];
                return View("Index");
            }

            TabelaMes notab;

            if (Session[tabindex] == null)
                notab = new TabelaMes(a);
            else
                notab = (TabelaMes)Session[tabindex];
            
            notab.Atualiza(m, a);
            Session[tarifmesindex] = notab.Tarifs;
            Session[tabindex] = notab;
            ViewData["tabelames"] = notab;

           
            

            return View("Index");
        }



       
        public ActionResult Load()
        {
            
            int m = DateTime.Today.Month;
            int a= DateTime.Today.Year;
            string tarifmesindex = "tarifmes" + m.ToString() + "a" + a.ToString();
            string tabindex = "tabela" + a.ToString();
            ViewData["mes"] = m;
            ViewData["ano"] = a;

            if (Session[tarifmesindex] != null)
            {
                ViewData["tabelames"] = Session[tabindex];
                return View("Index");
            }
             TabelaMes notab;
           

            if (Session[tabindex] == null)
               notab = new TabelaMes(a);
            else
               notab=(TabelaMes)Session[tabindex];
           

            notab.Atualiza(m,a);
            ViewData["tabelames"] = notab;
            Session[tabindex] = notab;
            Session[tarifmesindex] = notab.Tarifs;
            return View("Index");
        }


        public ActionResult editarif(FormCollection form)
        {
            
            string lop = form["input"];
            string[] split = lop.Split(new Char[] { '(', ')' });
            int m = (int)Session["tempmes"];
            int d; try { d = (int)Session["tempdia"]; }
            catch { }
            int a = (int)Session["tempano"];
            string tarifmesindex = "tarifmes" + m.ToString() + "a" + a.ToString();
            string j = "tabela" + a.ToString();
            Funcionario fun=new Funcionario();
            tarefa taredit = (tarefa)Session[split[1]];
            TabelaMes tab = (TabelaMes)Session[j];
            List<tarefa> tottaref = (List<tarefa>)Session[tarifmesindex];
            List<tarefa> tareparse = (List<tarefa>)Session["temporio"];
            
            DateTime adia = new DateTime(2012, 1, 1);


            if (split[0] == "Atualiza")
            {
                try { adia = new DateTime(Int32.Parse(form["Ano" + split[1]]), Int32.Parse(form["Mes" + split[1]]), Int32.Parse(form["Dia" + split[1]])); }
                catch
                {
                    ModelState.AddModelError("data" + split[1], "Data invalida");
                    ViewData["listtarefas"] = tareparse;
                    return View("Diaria");
                }

                if (form["opcao" + split[1]] == "1" && DateTime.Compare(DateTime.Today, adia) == 1)
                {
                    ModelState.AddModelError("data" + split[1], "Data invalida");
                    ViewData["listtarefas"] = tareparse;
                    return View("Diaria");
                }
                if (form["coment" + split[1]].Length > 210)
                {
                    ModelState.AddModelError("coment" + split[1], "Limite maximo de 210 caracteres!");
                    return View("Diaria");
                }

                if (form["opcao" + split[1]] == null || form["coment" + split[1]] == "")
                {
                    ModelState.AddModelError("coment" + split[1], "Adicione um comentario.");
                    ModelState.AddModelError("opcao" + split[1], "Escolha uma opção.");
                    ViewData["listtarefas"] = tareparse;
                    return View("Diaria");
                                    }
                else if (form["opcao" + split[1]] == "1")
                {
                    if (taredit.Nadd < taredit.Priori)
                    {
                       
                        taredit.Nadd=1;
                        tareparse.Remove(taredit);
                        taredit.Status1 = 1;
                        taredit.Prazo = adia;
                        taredit.Comentarios = form["coment" + split[1]];

                        tab.Atualiza(adia.Month, adia.Year);
                        tab.Atualiza(m, a);
                        Session[j] = tab;
                    }
                    else
                        ModelState.AddModelError("erreadia"+split[1], "Essa tarefa não pode mais ser adiada!");

                }
                else if (form["opcao" + split[1]] == "2")
                {
                                                   
                    tareparse.Remove(taredit);
                    taredit.Status1 = 3;
                    taredit.Comentarios = form["coment" + split[1]];
                    tareparse.Add(taredit);
                    tab.Atualiza(m, a);
                    Session[j] = tab;

                }
                Session["tarifmes" + m.ToString() + "a" + a.ToString()] = tab.Tarifs;
                ViewData["listtarefas"] = tareparse;
                return View("Diaria");

            }
            else
            {
                Login log = (Login)Session["login"];

                if (log.mec.Acesso > 0)
                {
                    tareparse.Remove(taredit);
                    taredit.Deletebanco();
                    tab.Atualiza(m, a);
                    Session["tarifmes" + m.ToString() + "a" + a.ToString()] = tab.Tarifs;
                }
                if ((string)Session["volta"] == "D")
                {
                    ViewData["listtarefas"] = tareparse;
                    return View("Diaria");
                }
                else {
                return RedirectToAction("Estatistic");
                }

                

            }

           
           
      

          
           
        }



        public ActionResult Estatistic()
        {
            DateTime ini = new DateTime((int)Session["tempano"],(int)Session["tempmes"],1);
            DateTime fim = new DateTime((int)Session["tempano"], (int)Session["tempmes"], DateTime.DaysInMonth((int)Session["tempano"], (int)Session["tempmes"]));
            BancodeDados bank = new BancodeDados();
            List<Funcionario> funcionarios = bank.ObterFunci();
            List<tarefa> tarefas = bank.ObterTarefa(ini,fim);

            ViewData["funci"] = funcionarios;
            ViewData["listtarefas"] = tarefas;

            return View("InfFuncio");
        }

        [HttpPost]
        public ActionResult Desbloq(FormCollection form)
        {
            Login log = (Login)Session["login"];
            string lop = form["bb"];
            string[] split = lop.Split(new Char[] { '[', ']' });
            Funcionario fun = (Funcionario)Session["a" + split[1]];
            if (log.mec.Acesso >= fun.Acesso)
            {              

                log.Desloqueia(fun.Username);
               
               

           }
       
            return RedirectToAction("Estatistic");
        }

        public ActionResult Voltar()
        {
            int a = (int)Session["tempano"];
            int m = (int)Session["tempmes"];
            string tabindex = "tabela" + a.ToString();
            string tarifmesindex = "tarifmes" + m.ToString() + "a" + a.ToString();

            ViewData["mes"] = m;
            ViewData["ano"] = a;
            if (Session[tarifmesindex] != null)
            {
                ViewData["tabelames"] = Session[tabindex];
                return View("Index");
            }

            TabelaMes notab = (TabelaMes)Session[tabindex];
            notab.Atualiza(m, a);
            Session[tarifmesindex] = notab.Tarifs;
            Session[tabindex] = notab;
            ViewData["tabelames"] = notab;




            return View("Index");
        }


    }
}
